package com.topscomm.mpm.script;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.topscomm.main.hessian.IBaseOperateRecordService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.*;
import com.topscomm.mpm.service.impl.MpmProjectService;
import com.topscomm.tap.common.DatacodeCache;
import org.springframework.transaction.annotation.Transactional;

import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.mpm.MpmScript;
import com.topscomm.mpm.service.impl.MpmProjectMilepostService;
import com.topscomm.mpm.service.impl.MpmProjectTaskFeedbackService;
import com.topscomm.mpm.service.impl.MpmProjectTaskService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.TapEntity;

public class MpmProjectTaskFeedbackScript extends MpmScript {

	/**
	 * 任务反馈结束后更新对应任务相关字段，对应里程碑及任务字段，对应项目字段
	 *
	 * @param service
	 * @param entity
	 * @throws Exception
	 */
	@Transactional
	public void projectTaskUpdate(ITapService service, TapEntity entity) throws Exception {
		// 审批节点实例
		CboApprovalNodeInsEntity nodeins = (CboApprovalNodeInsEntity) entity;
		String sourceid = ConvertUtil.convertToString(nodeins.getSourceid());
		MpmProjectTaskFeedbackService mpmProjectTaskFeedbackService = (MpmProjectTaskFeedbackService) SpringUtil.getBean("mpmProjectTaskFeedbackService");
		MpmProjectTaskService mpmProjectTaskService = (MpmProjectTaskService) SpringUtil.getBean("mpmProjectTaskService");
		MpmProjectMilepostService mpmProjectMilepostService = (MpmProjectMilepostService) SpringUtil.getBean("mpmProjectMilepostService");
		MpmProjectService mpmProjectService = (MpmProjectService) SpringUtil.getBean("mpmProjectService");
		// 查询反馈实体
		MpmProjectTaskFeedbackEntity mpmProjectTaskFeedbackEntity = mpmProjectTaskFeedbackService.queryById(sourceid);
		// 查询对应任务实体
		MpmProjectTaskEntity mpmProjectTaskEntity = mpmProjectTaskService.queryById(mpmProjectTaskFeedbackEntity.getTaskid());
		// 更新项目任务字段
		if(ObjectUtil.isEmpty(mpmProjectTaskEntity)) {
			return;
		}
		String taskstate = String.valueOf(mpmProjectTaskFeedbackEntity.getTaskstate());
		String taskschedule = mpmProjectTaskFeedbackEntity.getTaskschedule();
		mpmProjectTaskEntity.setTaskstate(taskstate);
		mpmProjectTaskEntity.setTaskschedule(taskschedule);
		mpmProjectTaskEntity.setActualenddate(mpmProjectTaskFeedbackEntity.getTaskactualenddate());
		mpmProjectTaskEntity.setTaskupdatedate(new Date());
		if (!StringUtil.isEmpty(mpmProjectTaskFeedbackEntity.getHavenamelist())) {
			mpmProjectTaskEntity.setHavenamelist(mpmProjectTaskFeedbackEntity.getHavenamelist());
		}
		if (!StringUtil.isEmpty(mpmProjectTaskFeedbackEntity.getPerformancescore())) {
			mpmProjectTaskEntity.setPerformancescore(mpmProjectTaskFeedbackEntity.getPerformancescore());
		}
		if (!StringUtil.isEmpty(mpmProjectTaskFeedbackEntity.getPerformancerank())) {
			mpmProjectTaskEntity.setPerformancerank(mpmProjectTaskFeedbackEntity.getPerformancerank());
		}
		if (!StringUtil.isEmpty(mpmProjectTaskFeedbackEntity.getReviewmeetname())) {
			mpmProjectTaskEntity.setReviewmeetname(mpmProjectTaskFeedbackEntity.getReviewmeetname());
		}
		if (!StringUtil.isEmpty(mpmProjectTaskFeedbackEntity.getGuorank())) {
			mpmProjectTaskEntity.setGuorank(mpmProjectTaskFeedbackEntity.getGuorank());
		}
		if (!StringUtil.isEmpty(mpmProjectTaskFeedbackEntity.getGuoscore())) {
			mpmProjectTaskEntity.setGuoscore(mpmProjectTaskFeedbackEntity.getGuoscore());
		}
		if (!StringUtil.isEmpty(mpmProjectTaskFeedbackEntity.getGuoposition())) {
			mpmProjectTaskEntity.setGuoposition(mpmProjectTaskFeedbackEntity.getGuoposition());
		}
		if (!StringUtil.isEmpty(mpmProjectTaskFeedbackEntity.getNankeeprank())) {
			mpmProjectTaskEntity.setNankeeprank(mpmProjectTaskFeedbackEntity.getNankeeprank());
		}
		if (!StringUtil.isEmpty(mpmProjectTaskFeedbackEntity.getNankeepscore())) {
			mpmProjectTaskEntity.setNankeepscore(mpmProjectTaskFeedbackEntity.getNankeepscore());
		}
		if (!StringUtil.isEmpty(mpmProjectTaskFeedbackEntity.getNanmoverank())) {
			mpmProjectTaskEntity.setNanmoverank(mpmProjectTaskFeedbackEntity.getNanmoverank());
		}
		if (!StringUtil.isEmpty(mpmProjectTaskFeedbackEntity.getNanmovescore())) {
			mpmProjectTaskEntity.setNanmovescore(mpmProjectTaskFeedbackEntity.getNanmovescore());
		}
		if (!StringUtil.isEmpty(mpmProjectTaskFeedbackEntity.getReviewmeetingdocument())) {
			mpmProjectTaskEntity.setReviewmeetingdocument(mpmProjectTaskFeedbackEntity.getReviewmeetingdocument());
		}
		Map<String, Object> taskMap = mpmProjectTaskEntity.convertToMap();
		taskMap.put("dateupdateflag", 1);
		mpmProjectTaskService.update(taskMap);
		// 若任务反馈的任务状态为完成或未完成关闭,则判断以下事情：是否需要更新项目状态；是否需要更新里程碑及任务状态
		if (MpmSystemConst.TaskStateCode.TaskCompleteCode.equals(mpmProjectTaskFeedbackEntity.getTaskstate()) ||
				MpmSystemConst.TaskStateCode.TaskIncompleteCloseCode.equals(mpmProjectTaskFeedbackEntity.getTaskstate())) {
			String milepostCode = mpmProjectTaskEntity.getMilepostcode();
			StringBufferProxy whereSql = new StringBufferProxy();
			String projectCode = mpmProjectTaskEntity.getProjectcode();
			// 任务已完成需要执行实时更新项目状态方法（方法会判断是否需要更新）
			mpmProjectService.updateAbnormalState(projectCode);
			// 查询该任务所属里程碑及任务下是否还有未开始、进行中的任务
			whereSql.appendLineSingle(" {0} = '{1}' and {2} in ('{3}','{4}') ", MpmProjectTaskEntity.FieldMilepostcode, milepostCode,
					MpmProjectTaskEntity.FieldTaskstate, MpmSystemConst.TaskStateCode.TaskNotStartCode, MpmSystemConst.TaskStateCode.TaskIncompleteCode);
			List<MpmProjectTaskEntity> mpmProjectTaskEntities = mpmProjectTaskService.queryByWhere(whereSql.toString());
			// 没有则把里程碑及任务状态改为已达成，并判断项目是否为里程碑及任务超期状态
			if (CollectionUtil.isEmpty(mpmProjectTaskEntities)) {
				whereSql.clear();
				whereSql.appendLineSingle(" {0} = {1} and enabled = 1 ", MpmProjectMilepostEntity.FieldOperatecode, milepostCode);
				MpmProjectMilepostEntity mpmProjectMilepostEntity = mpmProjectMilepostService.queryObjectByWhere(whereSql.toString());
				if (!ObjectUtil.isEmpty(mpmProjectMilepostEntity)) {
					mpmProjectMilepostEntity.setMilepoststate(1);
					mpmProjectMilepostEntity.setActualfinishtime(new Date());
					mpmProjectMilepostService.updateEntity(mpmProjectMilepostEntity);
					// 里程碑及任务置为已达成后需要执行实时更新项目状态方法（方法会判断是否需要更新）
					mpmProjectService.updateAbnormalState(projectCode);
				}
			}
			// 查询该任务对应的项目,判断是否需要更新项目状态至复盘阶段
			whereSql.clear();
			whereSql.appendSingle(" enabled = 1 and projectcode = '{0}' ", projectCode);
			MpmProjectEntity mpmProjectEntity = mpmProjectService.queryObjectByWhere(whereSql.toString());
			if(!ObjectUtil.isEmpty(mpmProjectEntity)) {
				mpmProjectTaskService.queryMilepostAllFinished(mpmProjectEntity);
			}
		}
	}

	public void sendTaskUpdateMessage(ITapService service, TapEntity entity){
		CboApprovalNodeInsEntity nodeins = (CboApprovalNodeInsEntity) entity;
		String sourceid = ConvertUtil.convertToString(nodeins.getSourceid());
		MpmProjectTaskFeedbackService mpmProjectTaskFeedbackService = (MpmProjectTaskFeedbackService) SpringUtil.getBean("mpmProjectTaskFeedbackService");
		MpmProjectTaskService mpmProjectTaskService = (MpmProjectTaskService) SpringUtil.getBean("mpmProjectTaskService");
		// 查询反馈实体
		MpmProjectTaskFeedbackEntity mpmProjectTaskFeedbackEntity = mpmProjectTaskFeedbackService.queryById(sourceid);
		// 查询对应任务实体
		MpmProjectTaskEntity mpmProjectTaskEntity = mpmProjectTaskService.queryById(mpmProjectTaskFeedbackEntity.getTaskid());
		// 如果是审查会任务的反馈且任务新增了附件，进行消息提醒
		mpmProjectTaskFeedbackService.sendAttachmentMessage(mpmProjectTaskFeedbackEntity);
		// 反馈后增加系统部监管任务提醒
		DatacodeCache datacodeCache = (DatacodeCache)SpringUtil.getBean("datacodeCache") ;
		List<Map<String, Object>> stateList = datacodeCache.getCodeListMap("MpmSystemTaskname", "", "sortcode");
		List<String> tasknameList = stateList.stream().map(e->ConvertUtil.convertToString(e.get("name"))).collect(Collectors.toList());
		String taskname = mpmProjectTaskEntity.getTaskname();
		if(tasknameList.indexOf(taskname) == -1) {
			return;
		}
		//List
		IBaseOperateRecordService baseOperateRecordService = (IBaseOperateRecordService)SpringUtil.getBean("baseOperateRecordService");
		String taskid = ConvertUtil.convertToString(mpmProjectTaskEntity.getId());
		String sourcetype = MpmProjectTaskEntity.tableName;
		String projectcode = mpmProjectTaskEntity.getProjectcode();
		String usercode = baseOperateRecordService.queryMarkedInfoByTask(sourcetype,taskid,projectcode);
		mpmProjectTaskService.sendTaskChangeMessage(usercode,projectcode,taskname,ConvertUtil.convertToLong(taskid));
	}


}
